<template>
  <div class="header-wrapper">
    <q-toolbar>
      <!-- 返回按钮 -->
      <slot name="left">
        <q-btn v-if="showBackButton" flat icon="arrow_back" @click="goBack" class="back-btn" />
      </slot>
      <q-toolbar-title class="title">
        <slot>{{ title }}</slot>
      </q-toolbar-title>
      <!-- 右侧内容，支持通过插槽传入 -->
      <div class="right-content">
        <slot name="right" />
      </div>
    </q-toolbar>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'
import { useRouter } from 'vue-router'

// 获取路由实例
const router = useRouter()

// 定义标题和显示返回按钮的 props
defineProps({
  title: {
    type: String,
    default: '',
  },
  showBackButton: {
    type: Boolean,
    default: true,
  },
})
const emit = defineEmits(['back'])

// 检查是否有监听 back 事件
const hasBackListener = () => {
  return emit('back').length > 0
}

const goBack = () => {
  if (hasBackListener()) {
    // 如果外部监听了 back 事件，则触发事件
    emit('back')
  } else {
    // 如果没有监听，则执行默认返回逻辑
    router.back()
  }
}
</script>

<style scoped>
.header-wrapper {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: white;
  color: black;
}

.back-btn {
  margin-right: 12px;
}

.title {
  flex: none;
  text-align: center;
  margin: 0 auto;
}

.right-content {
  min-width: 50px;
  margin-right: 12px;
}
</style>
